package com.gsy.iterator;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.SecureRandom;
import java.util.Objects;
import java.util.Random;

public class ForTest {
    public static void main(String[] args) {
        Class obj = ForTest.class;
        int len = 1000000000;
        try {
            Method method1 = obj.getMethod("testFori", int[].class);
            Method method2 = obj.getMethod("testForEach", int[].class);
            int arr[] = new int[len];
            Random  random = new SecureRandom();
            for (int i = 0; i < len; i++) {
                arr[i] = random.nextInt();
            }
            Object ob = obj.getConstructor().newInstance();
            System.out.println(getRunTime(method1,ob,arr));
            System.out.println(getRunTime(method2,ob,arr));
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
    public static long getRunTime(Method method,Object obj,Object... vars) {
        long start = System.currentTimeMillis();
        try {
            method.invoke(obj,vars);

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        return end - start;
    }
    public void testFori(int []arrs){
        int sum = 0;
        for (int i = 0; i < arrs.length; i++) {
            sum += arrs[i];
        }
    }
    public void testForEach(int arrs[]) {
        int sum = 0;
        for (int arr : arrs) {
            sum += arr;
        }
    }
}
